import user from '@/api/user'
import { getToken, setToken, removeToken, setName, removeName, setId, removeId } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
}

const actions = {
  saveName ({commit}, name) {
    commit('SET_NAME', name)
  },
  // user login
  login ({commit}, userInfo) {
    // console.log(userInfo)
    const {adminName, password} = userInfo
    return new Promise((resolve, reject) => {
      user.login({adminName: adminName.trim(), password: password}).then(res => {
        const {data} = res
        commit('SET_TOKEN', data.token)
        commit('SET_NAME', data.name)
        setToken(data.token)
        setName(data.name)
        setId(data.id)
        resolve()
      }).catch(err => {
        reject(err)
      })
    })
  },

  // get user info
  getInfo ({commit, state}) {
    return new Promise((resolve, reject) => {
      user.getInfo({token: state.token}).then(res => {
        const {data} = res
        if (!data) {
          reject('验证失败，请重新登录')
        }
        const {name, avatar} = data
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(err => {
        reject(err)
      })
    })
  },

  // user logout
  logout ({commit, state}) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      removeToken()
      removeName()
      removeId()
      resetRouter()
      this.$store.dispatch('tagsView/delAllViews', null, {root: true})
      resolve()
      // user.logout(state.token).then(() => {
      //   commit('SET_TOKEN', '')
      //   removeToken()
      //   resetRouter()
      //   resolve()
      // }).catch(err => {
      //   reject(err)
      // })
    })
  },

  // remove token
  resetToken ({commit}) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}

